//
//  GroupListVC.m
//  SelfDriving
//
//  Created by apple on 16/3/30.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "GroupListVC.h"
#import "MsgCell.h"
#import "BusinessService+User.h"
#import "GroupChatVC.h"
#import "XhwWebViewController.h"
@interface GroupListVC()<BaseTableDetelage,UITableViewDataSource,UITableViewDelegate,TCResultGroupListDelegate>
@property (weak, nonatomic) IBOutlet BaseTable *table;
@property (nonatomic,strong) NSMutableArray * positionFor4ModeImage;
@property (nonatomic,strong) NSMutableArray * positionFor9ModeImage;

@end
@implementation GroupListVC{
    NSMutableArray *data;
    UILabel *notlabel;
    NSMutableArray * imageArr; //优化性能
}
-(void)viewDidLoad{
    _positionFor4ModeImage = [NSMutableArray array];
    _positionFor9ModeImage = [NSMutableArray array];
    
    data = [NSMutableArray array];
    
//    _table.frame = CGRectMake(0, 100, SCRE_WIDTH, self.view.frame.size.height - 100);
    _table.bdelegate = self;
    [_table Refresh];
    self.navigationItem.title = @"我的群组";
    [self initData:0];
    
}
-(void)viewWillAppear:(BOOL)animated{
    
}
-(void)initData:(int)index{
    [[BusinessService shareInstance]sessionLists:[[NSMutableDictionary alloc]init] success:^(id result) {
        data = result;
        [self initImageposition];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
//        for (int i = 0; i<data.count ; i++) {
//            LoginResponseModel *  itemG = [data objectAtIndex:i];
//            NSMutableArray *imageArray = [NSMutableArray array];
//
//            for (int i=0; i<itemG.headlist.count; i++) {
//                NSMutableDictionary *dic = [itemG.headlist objectAtIndex:i];
//                UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
//                [ValidateHelper setImage:[dic objectForKey:@"headsmall"] img:img istoux:YES];
//                img.layer.cornerRadius = img.frame.size.width/2;
//                img.clipsToBounds = YES;
//                [imageArray addObject:img.image];
//            }
//            [imageArr addObject:[self makeGroupAvatar:imageArray]];
//        }
//            // 耗时的操作
//        dispatch_async(dispatch_get_main_queue(), ^{
//                // 更新界面
//            [_table reloadData];
//            });
//        });
        [_table reloadData];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
    
    
}
- (IBAction)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return data.count;
}
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return 50;
//}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    MsgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MsgCell"];
    
    LoginResponseModel *  itemG = [data objectAtIndex:indexPath.row];
    cell.content.text = itemG.name;
    //    cell.img.layer.cornerRadius = cell.img.frame.size.width/2;
    //    [ValidateHelper setImage:itemG.headImgUrlL img:cell.img istoux:YES];
    NSMutableArray *imageArray = [NSMutableArray array];
    
//    for (int i=0; i<itemG.headlist.count; i++) {
//        NSMutableDictionary *dic = [itemG.headlist objectAtIndex:i];
//        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
//        [ValidateHelper setImage:[dic objectForKey:@"headsmall"] img:img istoux:YES];
//        img.layer.cornerRadius = img.frame.size.width/2;
//        img.clipsToBounds = YES;
//        [imageArray addObject:img.image];
//    }
    
    //xhw2018-2-7
    CGFloat x = 0;
    CGFloat y = 0;
    for (int i=0; i<itemG.headlist.count; i++) {
        NSMutableDictionary *dic = [itemG.headlist objectAtIndex:i];
        if (i == 0) {
            x = 0;
            y = 0;
        }
        else if (i==1){
            x = ((35-1)/2)+1;
            y = 0;
        }
        else if (i == 2) {
            x = 0;
            y = ((35-1)/2)+1;
        }
        else if (i == 3) {
            x = ((35-1)/2)+1;
            y = ((35-1)/2)+1;
        }
        
        
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, 17, 17)];
        [ValidateHelper setImage:[dic objectForKey:@"headsmall"] img:img istoux:YES];
        img.layer.cornerRadius = img.frame.size.width/2;
        img.clipsToBounds = YES;
        [cell.img addSubview:img];
        
        cell.img.image = nil;
    }
    
//
//    [cell.img setImage:[self makeGroupAvatar:imageArray]];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LoginResponseModel*  itemG = [data objectAtIndex:indexPath.row];
    TCSession *model = [[TCSession alloc]init];
    model.typeChat = 200;
    model.name = itemG.name;
    model.ID = itemG.id;
    if (_type) {
        TCMessage* msg = [TCMessage newMessage];
        msg.typeChat = 300;
        msg.typeFile = 1;
        msg.from.name = [AppDelegate shareDelegate].user.nickname;
        msg.from.ID = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
        msg.from.head = [AppDelegate shareDelegate].user.headsmall;
        msg.to.ID =[NSString stringWithFormat:@"%@",model.ID];
        msg.to.name = model.name;
        msg.to.head = model.head;
        msg.typeFile = 1;
        msg.state = forMessageStateHavent;
        msg.body = [[TCTextMessageBody alloc] init];
        msg.bodyText.content = _content;
        [msg.from setExtendValue:@"从哪儿来的?" forKey:@"from扩展"];
        [msg.to setExtendValue:@"到哪儿去?" forKey:@"to扩展"];
        [msg.body setExtendValue:@"消息体的扩展" forKey:@"body扩展"];
        [msg setExtendValue:@"消息本身的扩展" forKey:@"msg扩展"];
        [[AppDelegate shareDelegate]sendMessage:msg];
        
        UINavigationController *navigationVC = self.navigationController;
        NSMutableArray *viewControllers = [[NSMutableArray alloc] init];
        //    遍历导航控制器中的控制器
        for (UIViewController *vc in navigationVC.viewControllers) {
            [viewControllers addObject:vc];
//            if ([vc isKindOfClass:[SVWebViewController class]]) { //xhw2018-3-12
            if ([vc isKindOfClass:[XhwWebViewController class]]) {
                break;
            }
        }
        //    把控制器重新添加到导航控制器
        [navigationVC setViewControllers:viewControllers animated:YES];
        
        
    }else{
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        GroupChatVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupChatVC"];
        searchResultDetailController.tcs = model;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    }
}











- (UIImage *)makeGroupAvatar: (NSMutableArray *)imageArray {
    //数组为空，退出函数
    if ([imageArray count] == 0){
        return nil;
    }
    
    UIView *groupAvatarView = [[UIView alloc]initWithFrame:CGRectMake(0,0,193,193)];
    groupAvatarView.backgroundColor = [UIColor whiteColor];
    
    for (int i = 0; i < [imageArray count]; i++){
        UIImageView *tempImageView;
        if ([imageArray count] < 5){
            tempImageView = [[UIImageView alloc]initWithFrame:[[_positionFor4ModeImage objectAtIndex:i]CGRectValue]];
        }
        else{
            tempImageView = [[UIImageView alloc]initWithFrame:[[_positionFor9ModeImage objectAtIndex:i]CGRectValue]];
        }
        UIImage *imgss = [imageArray objectAtIndex:i];
        imgss = [UIImage createRoundedRectImage:imgss size:imgss.size radius:imgss.size.width/2];
        [tempImageView setImage:[UIImage borderImg:imgss]];
        [groupAvatarView addSubview:tempImageView];
    }
    
    //把UIView设置为image并修改图片大小55*55
//    UIImage *reImage = [self scaleToSize:[self convertViewToImage:groupAvatarView]size:CGSizeMake(80, 80)];
    
    
    
    //xhw2018-2-6加
    UIView * v = groupAvatarView;
    CGSize s = v.bounds.size;

    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数。

    UIGraphicsBeginImageContextWithOptions(s, YES, [UIScreen mainScreen].scale);

    [v.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

//    UIImage *reImage = [self scaleToSize:image size:CGSizeMake(80, 80)];
    
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    CGSize size = CGSizeMake(80, 80);
    
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
    
    
    
//    return reImage;
}
-(UIImage*)convertViewToImage:(UIView*)v{
    
    CGSize s = v.bounds.size;
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数。
    
    UIGraphicsBeginImageContextWithOptions(s, YES, [UIScreen mainScreen].scale);
    
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

- (void)initImageposition{
    
    //初始化4图片模式和9图片模式
    for(int i = 0; i < 9; i++){
        CGRect tempMode4Rect;
        CGRect tempMode9Rect;
        float mode4PositionX = 0;
        float mode4PositionY = 0;
        float mode9PositionX = 0;
        float mode9PositionY = 0;
        
        switch (i) {
            case 0:
                mode4PositionX = 4;
                mode4PositionY = 4;
                mode9PositionX = 4;
                mode9PositionY = 4;
                break;
            case 1:
                mode4PositionX = 98.5;
                mode4PositionY = 4;
                mode9PositionX = 67;
                mode9PositionY = 4;
                break;
            case 2:
                mode4PositionX = 4;
                mode4PositionY = 98.5;
                mode9PositionX = 130;
                mode9PositionY = 4;
                break;
            case 3:
                mode4PositionX = 98.5;
                mode4PositionY = 98.5;
                mode9PositionX = 4;
                mode9PositionY = 67;
                break;
            case 4:
                mode9PositionX = 67;
                mode9PositionY = 67;
                break;
            case 5:
                mode9PositionX = 130;
                mode9PositionY = 67;
                break;
            case 6:
                mode9PositionX = 4;
                mode9PositionY = 130;
                break;
            case 7:
                mode9PositionX = 67;
                mode9PositionY = 130;
                break;
            case 8:
                mode9PositionX = 130;
                mode9PositionY = 130;
                break;
            default:
                break;
        }
        
        //添加4模式图片坐标到数组
        if (i < 4 ){
            tempMode4Rect = CGRectMake(mode4PositionX, mode4PositionY, 90.5, 90.5);
            [_positionFor4ModeImage addObject:[NSValue valueWithCGRect:tempMode4Rect]];
        }
        
        //添加4模式图片坐标到数组
        tempMode9Rect = CGRectMake(mode9PositionX, mode9PositionY, 59, 59);
        [_positionFor9ModeImage addObject:[NSValue valueWithCGRect:tempMode9Rect]];
    }
}

@end
